from flask import Flask, render_template, request, jsonify, redirect, url_for
from api.ap import api_run

app = Flask(__name__)

# 模拟用户数据库
users = {'admin': '123456', 'user': 'password'}

@app.route('/')
def index():
    return redirect(url_for('api_test'))  # 确保 api_test 视图函数已定义

@app.route('/api_test')
def api_test():
    return render_template('api_test.html')

@app.route('/api1', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        try:
            # 获取JSON数据
            data = request.get_json()
            way = data.get('way')
            url = data.get('url')
            head = data.get('head')
            body = data.get('body')
            li = api_run(way, url, head, body)
            # 验证用户
            if li[0] == 200:
                return jsonify({
                    'success': True,
                    'message': li[0],
                    "code": li[1]
                }), 200
            else:
                return jsonify({
                    'success': False,
                    'message': '用户名或密码错误'
                }), 401
        except Exception as e:
            return jsonify({
                'success': False,
                'message': f'服务器错误: {str(e)}'
            }), 500

    # GET请求返回登录页面
    return render_template('api_test.html')

if __name__ == '__main__':
    app.run(debug=True)